package library.http.progress;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

public class ProgressRequestBody extends RequestBody {
    //实际的待包装请求体
    private final RequestBody requestBody;
    //包装完成的BufferedSink
    private BufferedSink bufferedSink;
    private final ProgressPublisher publisher;

    public ProgressRequestBody(RequestBody requestBody, final ProgressPublisher publisher) {
        this.requestBody = requestBody;
        this.publisher = publisher;
    }

    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return requestBody.contentLength();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            //包装
            bufferedSink = Okio.buffer(sink(sink));
        }
        //写入
        requestBody.writeTo(bufferedSink);
        //必须调用flush，否则最后一部分数据可能不会被写入
        bufferedSink.flush();

    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            //当前写入字节数
            long range = 0L;
            //总字节长度，避免多次调用contentLength()方法
            long length = -1L;

            long lastRange = -1L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                if (range == 0) {
                    publisher.flagStart();
                }
                try {
                    super.write(source, byteCount);
                } catch (IOException e) {
                    if (publisher != null) {
                        publisher.cancel();
                    }
                    throw e;
                }
                range += byteCount;
                if (length < 0)
                    length = contentLength();//如果contentLength()不知道长度，会返回-1
                if (publisher != null && length >= 0 && lastRange != range) {
                    publisher.publishProgress(lastRange = range, length);
                }
            }
        };
    }


}